package kt_test.util

import android.content.Context
import kt_test.room.database.OxygenDatabase
import kt_test.room.entity.OxygenSampleEntity
import kt_test.room.entity.UserInfoEntity
import kotlinx.coroutines.*
import java.text.SimpleDateFormat
import java.util.*

object OxygenSampleSaver {
    fun insertSpo2ToRoom(context: Context, spo2: Float) {
        val timestamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
        val userId = "U1001" // 这里临时用默认用户

        CoroutineScope(Dispatchers.IO).launch {
            val db = OxygenDatabase.getDatabase(context)
            val userDao = db.userInfoDao()

            // 若用户不存在则插入默认用户
            if (userDao.getById(userId) == null) {
                userDao.insert(UserInfoEntity(userId, "男", 70))
            }

            val sample = OxygenSampleEntity(
                userId = userId,
                time = timestamp,
                spo2 = spo2.toDouble()
            )
            db.oxygenSampleDao().insertSamples(listOf(sample))  // ✅ 修正
        }
    }
}
